//
//  TabHelperTableViewController.swift
//  kz
//
//  Created by Tech_001 on 10/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh

class TabHelperTableViewController: UITableViewController{
    let rc: MJRefreshHeader? = MJRefreshNormalHeader()
   var balanceButton: UIButton?
    override func viewDidLoad() {
        super.viewDidLoad()
      //  ToolHelper.statisticsPage(pageName: "助手页面")
        rc!.setRefreshingTarget(self, refreshingAction: #selector(self.pullToRefresh))
        self.tableView.mj_header = rc
        self.tableView.setNeedsLayout()
        self.tableView.layoutIfNeeded()
        
        /**** Balance ****/
        let balanceButton = UIButton(type: .custom)
        balanceButton.setTitle("Fetchin", for: .normal)
        balanceButton.setImage(UIImage(named: "icon_nav_right_amount"), for: .normal)
        balanceButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
        balanceButton.setTitleColor(UIColor.white, for: .normal)
        balanceButton.titleLabel?.font = UIFont(name: balanceButton.titleLabel!.font.fontName, size: 14)
        self.balanceButton = balanceButton
        
        let barItem = UIBarButtonItem(customView: balanceButton)
        
        self.navigationItem.setRightBarButton(barItem, animated: true)
        balanceButton.addTarget(self, action: #selector(self.pushWebViewTransfer), for: .touchUpInside)
        /*** Balance ***/
        
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
       topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        /**** Balance ****/
        
        self.refreshBalance()
    }
    func refreshBalance(){
        if UserHelper.getLoginStatus() {
            if let withBalance=GlobalInfo.memberInfoData!["balance"] as? String {
                  if withBalance != ""{
                    let  balance: Double = Double(withBalance)!
                    self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                    let size = self.balanceButton!.intrinsicContentSize
                    balanceButton!.frame.size = CGSize(width: size.width, height: 33)
                  }else{
                     self.balanceButton?.setTitle(String(format: "0.00"), for: .normal)
                 }
              
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
        }
    }
    
    
    
    @objc func pushWebViewTransfer(){
        if  GlobalInfo.isPlatformMainhtml == nil || GlobalInfo.isPlatformMainhtml != false{
            self.navigateWebView(toPath: "/walletm/transfer", "",sign: true)
        }else{
            let vc = MainAccountVC()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    /**** Others ****/
    func navigateWebView(toPath: String, _ title: String,sign:Bool){
        print("路径\(toPath)")
        let goNext: WebViewController = WebViewController.init()
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        goNext.url = url
        goNext.title = title
        goNext.signLoging=sign
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
        
    }
    /**** View Actions ****/
    @objc func loginRegisterButtonClick(){
         setRootLoginVC()
        //GlobalInfo.mainTabBarController?.navigationController?.popToRootViewController(animated: true)
        //        self.dismiss(animated: true, completion: nil)
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return GlobalInfo.helperInfoData!.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath as IndexPath) as! TabHelperTableViewCell
        let helper = GlobalInfo.helperInfoData![indexPath[1]]
        cell.helperTitle.text = helper["title"] as? String
        cell.helperDescription.text = helper["content"] as? String
    //    cell.helperImageView?.image = UIImage(named: "img_default_60")
        if let imageUrlStr = helper["imgurl"] as? String {
            let imageUrl = URL.init(string: imageUrlStr)

            cell.helperImageView?.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "img_default_60"), options: .refreshCached, completed: {(img, error, type, url) in
                
            })
//            RequestHelper.get((imageUrl?.host!)!, atPath: (imageUrl?.path!)!, withCompletion: { data in
//                DispatchQueue.main.async {
//                    cell.helperImageView?.image = UIImage(data: data)
//                }
//            }, withError: { error in
//                print(error)
//            })

        }
        
        return cell
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getUserInfo()
    }
    //获取会员信息
    func getUserInfo() -> Void {
        if UserHelper.getLoginStatus() {
            NetWorkRequest(API.memberInfoUL(url: "face82b",ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
                if(statusCode == 200){
                    //取出data的数据并转化为字典数据
                    let dataDict = responseData["data"].dictionaryObject
                    //获取到状态值
                    let statusStringJson = responseData["status"]
                    //把状态值的字符串转为int值
                    let statusString = Int("\(statusStringJson)")
                    //获取到传递过来的msg
                    let msgStringJson = responseData["msg"]
                    //把msgStringJson转为字符串
                    let msgString = "\(msgStringJson)"
                    //判断是否相等的
                    if(statusString == 0){
                        let memberInfoArray = dataDict?["response"] as? [String:Any] ?? [:]
                        GlobalInfo.memberInfoData = memberInfoArray
                        print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
                        DispatchQueue.main.async {
                            self.refreshBalance()
                            
                        }
                    }else{
                        DispatchQueue.main.async {
                            //弹出报错后的问题
                            UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                        }
                    }
                }else{
                    DispatchQueue.main.async {
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                    }
                }
            },failed: {(faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    if reCode == "21002"{
                        UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
            }
            ){() -> (Void) in
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                }
            }
            
//            RequestHelper.get(atPath: "/clientsAPIs/memberInfoUL", withCompletion: { data in
//                let memberInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//                print("获取用户信息")
//                GlobalInfo.memberInfoData = memberInfoArray
//                print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
//                DispatchQueue.main.async {
//                    self.refreshBalance()
//
//                }
//
//
//            }, withError: { error in
//                 UIHelper.alertSimpleMessage(about: "获取用户信息失败,\(getErrorString())", withDescription: "", in: self)
//            })
        //这个是判断的括号
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let helper = GlobalInfo.helperInfoData![indexPath[1]]
        let url = helper["url"] as! String
        let title = helper["title"] as! String;
        //这里加权限
        if helper["type"] !=  nil{
            // Skip helper app
        }else{
            let goNext: WebViewController = WebViewController.init()
            
            if(title=="体育直播"){
                               
                goNext.url = url.replacingOccurrences(of: "https", with: "http")
                print("路径\(url)")
                goNext.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(goNext, animated: true)
                
            }else {
                                
                if title == "亚运专栏"{
                    goNext.isLoadjsCode = true
                }
                print("路径\(url)")
                goNext.url = url
                goNext.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(goNext, animated: true)
            }
        }
    }
    
    @objc func pullToRefresh(){
        RequestHelper.get(GlobalInfo.resDomain, atPath: GlobalInfo.getGameJson, withCompletion: { data in
            let gameInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            //GlobalInfo.helperInfoData = gameInfoArray["helper"] as? [[String:Any]]
            print("数据\(gameInfoArray)")
            GlobalInfo.gameInfoData = gameInfoArray
            
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.rc?.endRefreshing()
            }
            
        }, withError: { error in
            DispatchQueue.main.async {
                self.rc?.endRefreshing()
                UIHelper.alertSimpleMessage(about: "无法获取配置文件信息，请联系客服\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
}
